<!--  -->
<template>
  <div class="new-mirror">
    <div class="new-mirror-title">
      <div class="mirror-title-ico">
        <img src="@/common/image/new-mirror-ico.png" alt="">
      </div>
      <h2>新建镜像</h2>
    </div>
    <div class="new-mirror-con">
      <el-form
        label-position="top"
        class="form"
        :model="datasetForm"
        ref="datasetForm"
        :rules="rulesForm"
        @submit.native.prevent>
        <el-form-item label="" lable-width="0px" class="form-width-box" prop="name">
          <div class="form-label"><i class="mirror-ico mirror-ico-name"></i>镜像名称</div>
          <el-input v-model="datasetForm.name" placeholder="须以字母开头，支持字母、数字及标点符号"></el-input>
        </el-form-item>
        <div class="form-width-box">
          <el-row :gutter="36">
            <el-col :span="12">
              <el-form-item label="" lable-width="0px">
                <div class="form-label"><i class="mirror-ico mirror-ico-lang"></i>编程语言</div>
                <el-select v-model="datasetForm.programming" placeholder="请选择">
                  <el-option
                    v-for="item in programmingOption"
                    :key="item.name"
                    :label="item.name"
                    :value="item.id">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="" lable-width="0px">
                <div class="form-label"><i class="mirror-ico mirror-ico-algorithm"></i>算法框架</div>
                <el-select v-model="datasetForm.algorithm" placeholder="请选择">
                  <el-option
                    v-for="item in algorithmOption"
                    :key="item.name"
                    :label="item.name"
                    :value="item.id">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
        </div>
        <div class="upload-file-wrap">
          <h4 class="form-label">
            上传dockerfile
          </h4>
          <!-- <el-button size="medium" class="action-button" @click="clickUploadFile"><i class="upload-file-ico"></i>点击上传文件</el-button>
          <ul class="form-width-box upload-file-con">
            <li class="upload-file-item"><i class="icon"></i>123
              <span class="upload-file-item-btn"></span>
            </li>
          </ul> -->
          <el-upload
            class="upload-demo"
            ref="upload"
            action="string"
            :http-request="requestUpload"
            :before-upload="beforeUpload"
            :on-preview="handlePreview"
            :on-remove="handleRemove"
            :on-change="handleChange"
            :on-success="handleSuccess"
            :on-exceed="handleExceed"
            :limit="1"
            :auto-upload="false">
            <el-button size="medium" class="action-button"><i class="upload-file-ico"></i>点击上传文件</el-button>
          </el-upload>
          <!-- <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em>     </div> -->
          <!-- <el-button slot="trigger" size="small" type="primary">选取文件</el-button> -->
          <!-- <el-button style="margin-left: 10px;" size="small" type="success" @click="submitUpload">上传到服务器</el-button> -->
          <!-- <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div> -->
        </div>
        <el-form-item label="" lable-width="0px" class="mirror-introduction">
          <div class="form-label"><i></i>镜像简介</div>
          <editor
            v-show="mirrorDesc"
            ref="tuiEditor"
            v-model="datasetForm.desc"
            :options="editorOptions"
            previewStyle="vertical"
            height="240px"
          />
          <!-- <el-input type="textarea" v-model="datasetForm.desc"></el-input> -->
        </el-form-item>
        <el-form-item class="submit-generate">
          <el-button type="primary" @click="submitUpload('datasetForm')">提交生成</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
import 'tui-editor/dist/tui-editor.css'
import 'tui-editor/dist/tui-editor-contents.css'
import 'codemirror/lib/codemirror.css'
import { Editor } from '@toast-ui/vue-editor'

import { createUserImage } from '@/api/mirror'
import { frameworkGetList, languageGetList } from '../../api/image'
export default {
  data () {
    var validateName = (rule, value, callback) => {
      var reg1 = /.*[\u4e00-\u9fa5\u3002|\uff1f|\uff01|\uff0c|\u3001|\uff1b|\uff1a|\u201c|\u201d|\u2018|\u2019|\uff08|\uff09|\u300a|\u300b|\u3008|\u3009|\u3010|\u3011|\u300e|\u300f|\u300c|\u300d|\ufe43|\ufe44|\u3014|\u3015|\u2026|\u2014|\uff5e|\ufe4f|\uffe5]+.*$/
      var reg2 = /^[a-zA-Z]{1}[\S\s]*$/
      if (reg1.test(value)) {
        callback(new Error('镜像名称仅支持字母、数字及标点符号'))
      } else if (!reg2.test(value)) {
        callback(new Error('镜像名称须以字母开头'))
      } else if (/\s/.test(value)) {
        callback(new Error('镜像名称不能含有空格'))
      // } else if (!/^[a-zA-Z0-9-_.?!,:@)("'}{]*$/.test(value)) {
      } else if (!/^[a-zA-Z0-9-_.?!,:@)("'}{\u005b\u005d]*$/.test(value)) {
        callback(new Error('镜像名称仅支持字母、数字及标点符号'))
      } else {
        callback()
      }
    }
    return {
      mirrorDesc: true,
      datasetForm: {
        name: '',
        programming: '',
        algorithm: '',
        desc: ''
      },
      rulesForm: {
        name: [
          { required: true, message: '请输入镜像名称', trigger: 'blur' },
          { validator: validateName },
          { max: 50, message: '名称长度须在1到50个字符之间' }
        ]
      },
      programmingOption: [],
      algorithmOption: [],
      fileList: [],
      submitGeneratebtn: true,
      editorOptions: {
        hideModeSwitch: true
      }
    }
  },

  components: {
    'editor': Editor
  },

  // computed: {},

  mounted () {
    this._languageGetList()
    this._frameworkGetList()
    this.$nextTick(() => {
      this.$refs.tuiEditor.invoke('setValue', this.datasetForm.desc)
      this.$refs.tuiEditor.invoke('scrollTop', 1)
    })
  },

  methods: {
    // 上传前的判定
    beforeUpload (file) {
      const isLt2M = file.size / 1024 / 1024 < 2
      if (!isLt2M) {
        this.$message({ message: '文件大小不能超过2M！', showClose: true, type: 'error' })
      }
      return isLt2M
    },
    // 开始上传文件
    requestUpload (file) {
      let fd = new FormData()
      fd.append('file', file.file)
      fd.append('name', this.datasetForm.name)
      fd.append('content', this.datasetForm.desc)
      fd.append('contentMk', this.datasetForm.desc)
      fd.append('languageId', this.datasetForm.programming)
      fd.append('frameworkId', this.datasetForm.algorithm)
      createUserImage(fd).then(res => {
        if (res.message.code === 0) {
          this.$message({ message: '提交成功，正在生成镜像文件！', showClose: true, type: 'success' })
          this.$router.push({ path: '/personalmirror' })
        } else {
          this.$message({ message: res.message.message, showClose: true, type: 'error' })
        }
      })
      return true
    },
    // 点击确定后判断并执行上传
    submitUpload (agm) {
      this.$refs[agm].validate((valid) => {
        if (valid) {
          if (this.datasetForm.desc === '') {
            this.$message.warning('请输入镜像简介')
            return false
          } else {
            if (this.submitGeneratebtn) {
              this.$message.warning('请上传dockerfile文件')
            } else {
              this.$refs.upload.submit()
            }
          }
        } else {
          return false
        }
      })
    },
    // 限制上传数量弹框
    handleExceed (files, fileList) {
      this.$message.warning('最多只能上传1个文件')
    },
    // 删除上传文件
    handleRemove (file, fileList) {
      if (fileList.length > 0) {
        this.submitGeneratebtn = false
      } else {
        this.submitGeneratebtn = true
      }
    },
    handlePreview (file) {},
    // 上传成功
    handleSuccess (response, file, fileList) {},
    // 上传文件list改变时
    handleChange (file, fileList) {
      if (fileList.length > 0) {
        this.submitGeneratebtn = false
        const isLt2M = file.size / 1024 / 1024 < 2
        if (!isLt2M) {
          this.$refs.upload.clearFiles()
          this.$message({ message: '文件大小不能超过2M！', showClose: true, type: 'error' })
        }
        return isLt2M
      } else {
        this.submitGeneratebtn = true
      }
    },
    // 获取编程语言list（接口）
    _languageGetList () {
      languageGetList().then(res => {
        if (res.message.code === 0) {
          this.programmingOption = [...res.data]
          this.datasetForm.programming = this.programmingOption[0].id
        }
      })
    },
    // 获取算法框架list（接口）
    _frameworkGetList () {
      frameworkGetList().then(res => {
        if (res.message.code === 0) {
          this.algorithmOption = [...res.data]
          this.datasetForm.algorithm = this.algorithmOption[0].id
        }
      })
    }
  }
}

</script>
<style lang="stylus">
$fontcolor = #2D323B
.new-mirror
  width 100%
  margin 0 auto
  max-width 1162px
  padding-left 154px
  box-sizing border-box
  background #999999
  padding-top 69px
  .mirror-ico
    width 12px
    height 12px
    margin-top 4px
    margin-right 6px
    display inline-block
    &.mirror-ico-name
      background url(../../common/image/icon/mirror-ico-name.png) no-repeat center
      background-size 12px 12px
    &.mirror-ico-lang
      background url(../../common/image/icon-project/icon-project-language.png) no-repeat center
      background-size 12px 12px
    &.mirror-ico-algorithm
      background url(../../common/image/icon/mirror-ico-algorithm.png) no-repeat center
      background-size 12px 12px
  .new-mirror-title
    display flex
    padding-bottom 53px
    .mirror-title-ico
      width 130px
      height 70px
      margin-right 38px
      img
        width 100%
        height 100%
    h2
      width auto
      font-weight bold
      padding-top 28px
      color $fontcolor
      font-size 28px
      line-height 40px
  .new-mirror-con
    width 650px
    margin-left 168px
    .form
      .form-width-box
        width 433px
      .form-label
        font-size 14px
        line-height 20px
        color $fontcolor
        padding-bottom 11px
        font-weight bold
      .el-form-item
        padding-bottom 24px
      .upload-file-wrap
        padding-bottom 24px
        .action-button
          font-size 14px
          line-height 20px
          color #676767
          display flex
          align-items center
          .upload-file-ico
            width 12px
            height 12px
            margin-top 3px
            margin-right 7px
            display inline-block
            background url(../../common/image/icon/upload-file.png) no-repeat center
            background-size 12px 12px
          &.el-button--medium
            padding 0
            padding 10px 48px
        .upload-file-con
          padding 20px 0 8px
          .upload-file-item
            font-size 14px
            line-height 20px
            color $fontcolor
            .icon
              width 12px
              height 12px
              margin 3px 8px 0 13px
              display inline-block
              background url(../../common/image/icon/upload-file.png) no-repeat center
              background-size 12px 12px
            .upload-file-item-btn
              float right
              width 12px
              height 12px
              margin 3px 8px 0 13px
              display inline-block
              background url(../../common/image/icon/upload-file.png) no-repeat center
              background-size 12px 12px
            &:hover
              background #F4F7F8
            &:hover .upload-file-item-btn
                background url(../../common/image/icon-project/project-edit-box.png) no-repeat center
      .mirror-introduction
        &.el-form-item
          padding-bottom 0
      .submit-generate
        padding-top 10px
        .el-button
          padding 9px 70px
          font-size 16px
          line-height 22px
          color #ffffff
.upload-demo
  .el-upload-list__item
    &:hover .el-upload-list__item-status-label
      display none
    .el-upload-list__item-status-label
      display block
</style>
